package com.deltachi.lateplates;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

public class GoogleAuthentication {
	private final String gaeAppBaseUrl = "http://dxlateplates.appspot.com/";
	private final String gaeAppLoginUrl = gaeAppBaseUrl + "_ah/login";
	private final String googleLoginUrl = "https://www.google.com/accounts/ClientLogin";
	private final String service = "ah"; 
	public Cookie getAuthCookie() {
		return authCookie;
	}



	public void setAuthCookie(Cookie authCookie) {
		this.authCookie = authCookie;
	}

	private Cookie authCookie = null;
	
	
	//sample function that makes an http request and downloads 
	//the result providing the auth cookie.
	public String GetLoggedIn() throws IOException
	{

		String result;
		String destUrl = "http://app.nimbits.com/nimbits/Service/user"; 
		URL url = new URL(destUrl);
		URLConnection conn = url.openConnection ();
		Log.v("GetLoggedIn authCookie", authCookie.getValue());
		if (authCookie != null)
		{
		conn.addRequestProperty("Cookie",authCookie.getName() + "=" + authCookie.getValue());
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		StringBuffer sb = new StringBuffer();
		String line;
		while ((line = rd.readLine()) != null)
		{
			sb.append(line);
		}
		rd.close();
		result = sb.toString();
		}
		else
		{
			result = "false";
		}
		Log.v("GetLoggedIn", result);
		return result;
	}
	
	public static GoogleAuthentication getNewGoogleAuthentication()
	  {
		
		ref = new GoogleAuthentication();		
	    return ref;
	  }
	
	public static GoogleAuthentication getGoogleAuthentication()
	  {
	    if (ref == null)
	        // it's ok, we can call this constructor
	        ref = new GoogleAuthentication();		
	    return ref;
	  }
 
	private GoogleAuthentication()
	{
		
	}
	
	public Object clone()
	throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

  private static GoogleAuthentication ref;
	
  
  private String getToken(Context context)
  {
	  AccountManager mgr = AccountManager.get(context); 
	   Account[] accts = mgr.getAccountsByType("com.google"); 
	   Account acct = accts[0];
	   Log.v("Account", acct.name);
	   AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, "ah", null, (Activity) context, null, null);
	   Bundle authTokenBundle = null;
	try {
		authTokenBundle = accountManagerFuture.getResult();
	} catch (OperationCanceledException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (AuthenticatorException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	   String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
	   Log.v("TOKEN", authToken);
	   
  return authToken;
  
  
  }
  
  
  public boolean ConnectClean(Context context)  
	{
		boolean retVal = true;
		
		
		  Log.v("ConnectClean", "Call");
		 
				try {
					String authToken = getToken(context);
					authCookie = getAuthCookie(authToken);
				} catch (MalformedURLException e) {
					retVal= false;
				} catch (ProtocolException e) {
					retVal= false;
				} catch (UnsupportedEncodingException e) {
					retVal= false;
				} catch (ClientProtocolException e) {
					retVal= false;
				} catch (IOException e) {
					retVal= false;
				}
				
			
			
		 
		return retVal;
	}
  
  
	public boolean Connect(Context context)  
	{
		boolean retVal = true;
		
		
		if (authCookie == null)
		{
			
		 
				try {
					String authToken = getToken(context);
					authCookie = getAuthCookie(authToken);
				} catch (MalformedURLException e) {
					retVal= false;
				} catch (ProtocolException e) {
					retVal= false;
				} catch (UnsupportedEncodingException e) {
					retVal= false;
				} catch (ClientProtocolException e) {
					retVal= false;
				} catch (IOException e) {
					retVal= false;
				}
				
			
			
		}
		return retVal;
	}
	
//	private   String GetToken(String googleAccount, String googlePassword) throws MalformedURLException, ProtocolException, UnsupportedEncodingException, IOException
//	{
//		String token = null;
//		HttpURLConnection h =  GetConnection(googleAccount,googlePassword);
//		token= extractAuthTokenFromResponse(h);
//		return token;
//	}

	
	private   Cookie getAuthCookie(String authToken) throws ClientProtocolException, IOException {
		
		Log.v("getAuthCookie", "call " +authToken );
		DefaultHttpClient httpClient = new DefaultHttpClient();
		Cookie retObj = null;
		String cookieUrl = gaeAppLoginUrl + "?continue=" 
			+ URLEncoder.encode(gaeAppBaseUrl,"UTF-8") + "&auth=" + URLEncoder.encode 
			(authToken,"UTF-8"); 
		Log.v("getAuthCookie", "cookieUrl " +cookieUrl );
		HttpGet httpget = new HttpGet(cookieUrl);
		HttpResponse response = httpClient.execute(httpget);
		if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK ||
				response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {

			if (httpClient.getCookieStore().getCookies().size() > 0) {
				retObj=   httpClient.getCookieStore().getCookies().get(0);
			}

		}
		
		Log.v("getAuthCookie", "returns " +retObj.getValue() );
		
		return retObj;
		 
	}
	
//	private   HttpURLConnection GetConnection(String username, String password)
//	throws MalformedURLException, IOException, ProtocolException,
//	UnsupportedEncodingException {
//		HttpURLConnection urlConnection;
//		URL url = new URL(googleLoginUrl);
//		urlConnection = (HttpURLConnection) url.openConnection();
//		urlConnection.setRequestMethod("POST");
//		urlConnection.setDoInput(true);
//		urlConnection.setDoOutput(true);
//		urlConnection.setUseCaches(false);
//		urlConnection.setRequestProperty("Content-Type",
//		"application/x-www-form-urlencoded");
//		StringBuilder content = new StringBuilder();
//		content.append("Email=").append(username);
//		content.append("&Passwd=").append(password);
//		content.append("&service=").append(service);
//
//		OutputStream outputStream = urlConnection.getOutputStream();
//		outputStream.write(content.toString().getBytes("UTF-8"));
//		outputStream.close();
//		return urlConnection;
//	}
//	private   String extractAuthTokenFromResponse(HttpURLConnection urlConnection)
//	throws IOException {
//		int responseCode = urlConnection.getResponseCode();
//		System.out.println(responseCode);
//		StringBuffer resp = new StringBuffer(); 
//		if (responseCode == HttpURLConnection.HTTP_OK) {
//			InputStream inputStream = urlConnection.getInputStream();
//
//			BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
//			String line; 
//
//
//			while ((line = rd.readLine()) != null) { 
//			 
//				if(line.startsWith("Auth="))
//				{
//					resp.append(line.substring(5)); 
//				 
//				}
//
//			} 
//
//			rd.close(); 
//
//
//		}
//		return resp.toString();
//	}
}
